package com.hisan.freeride.home.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.View.OnClickListener;

import com.alibaba.sdk.android.push.CommonCallback;
import com.bumptech.glide.Glide;
import com.hisan.freeride.R;
import com.hisan.freeride.common.base.AppConfig;
import com.hisan.freeride.common.base.BaseAppLication;
import com.hisan.freeride.common.base.BaseFragment;
import com.hisan.freeride.common.callback.NoDialogCallback;
import com.hisan.freeride.common.utils.CacheUtils;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.utils.GsonUtils;
import com.hisan.freeride.common.utils.utils.TokenUtils;
import com.hisan.freeride.databinding.WoBinding;
import com.hisan.freeride.home.activity.CartCertificationActivity;
import com.hisan.freeride.home.activity.CommentActivity;
import com.hisan.freeride.home.activity.DataActivity;
import com.hisan.freeride.home.activity.InstalActivity;
import com.hisan.freeride.home.activity.InsuranceActivity;
import com.hisan.freeride.home.activity.LoginActivity;
import com.hisan.freeride.home.activity.RealNameActivity;
import com.hisan.freeride.home.activity.RecommendActiivity;
import com.hisan.freeride.home.activity.RotationActivity;
import com.hisan.freeride.home.activity.WoMessageActivity;
import com.hisan.freeride.home.model.UserData;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 创建时间 : 2017/11/13
 * 创建人：yangyingqi
 * 公司：嘉善和盛网络有限公司
 * 备注：我的页面
 */
public class WoFragment extends BaseFragment<WoBinding> implements CommonCallback {
    //拨打电话权限返回码
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;
    String token="";
    public static WoFragment getInstance(){
        WoFragment wofragment=null;
        if (wofragment==null){
            wofragment=new WoFragment();
        }
        return wofragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.wo;
    }

    @Override
    protected void initView() {}

    @Override
    protected void initEvent() {
     token= CacheUtils.getInstance().getString("token");
        mBinding.logo.setOnClickListener(v -> {
            if (!CollectionUtils.isNullOrEmpty(token))
            startActivityForResult(DataActivity.class,99,null,true);
        else startActivityForResult(LoginActivity.class,99,null,true);});
        mBinding.selectComment.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showSuccessToast("正在开发,敬请期待！");
            }
        });
        mBinding.selectInsurance.setOnClickListener(v -> {
            if (!CollectionUtils.isNullOrEmpty(token))
                startActivityForResult(InsuranceActivity.class,99,null,true);
            else startActivityForResult(LoginActivity.class,99,null,true);
        });
        mBinding.welfare.setOnClickListener(v -> showSuccessToast("正在开发,敬请期待！"));
        mBinding.newMs.setOnClickListener(v -> {
            if (!CollectionUtils.isNullOrEmpty(token))
                startActivityForResult(WoMessageActivity.class,99,null,true);
            else startActivityForResult(LoginActivity.class,99,null,true);});
                mBinding.woAppraise.setOnClickListener(v -> {
            if (!CollectionUtils.isNullOrEmpty(token))
                startActivityForResult(CommentActivity.class,99,null,true);
            else startActivityForResult(LoginActivity.class,99,null,true);});
        mBinding.recommend.setOnClickListener(v -> {
            if (!CollectionUtils.isNullOrEmpty(token))
                startActivityForResult(RecommendActiivity.class,99,null,true);
            else startActivityForResult(LoginActivity.class,99,null,true);});
   //    mBinding.welfare.setOnClickListener(v -> {startActivityForResult(IntegralMallActivity.class,99,null,true);});
        mBinding.cart.setOnClickListener(v -> {   RotationActivity.skip(getActivity(), AppConfig.simple);});
        mBinding.tel.setOnClickListener(v -> getmDialog("是否打开手机拨号?","取消","确定").show());
        mBinding.instal.setOnClickListener(v ->{startActivityForResult(InstalActivity.class,99,null,true);});
        mBinding.loginNo.setOnClickListener(v -> startActivityForResult(LoginActivity.class,99,null,true));
        mBinding.score.setOnClickListener(v -> {
            if (!CollectionUtils.isNullOrEmpty(token))
                startActivityForResult(DataActivity.class,99,null,true);
            else startActivityForResult(LoginActivity.class,99,null,true);});
    }

    @Override
    public void onOk() {
        // 检查是否获得了权限（Android6.0运行时权限）
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){
            // 没有获得授权，申请授权
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.CALL_PHONE)) {
                // 弹窗需要解释为何需要该权限，再次请求授权
                showToast("请在应用中开启电话权限");
                // 帮跳转到该应用的设置界面，让用户手动授权
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);
            }else{
                // 不需要解释为何需要该权限，直接请求授权
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{Manifest.permission.CALL_PHONE},
                        MY_PERMISSIONS_REQUEST_CALL_PHONE);
            }
        }else {
            // 已经获得授权，可以打电话
            if (!CollectionUtils.isNullOrEmpty(AppConfig.tel)){
                CallPhone(AppConfig.tel);
            }
        }
    }

    @Override
    public void onCancel() {
        if (mDialog.isShowing())mDialog.dismiss();
    }

    private void CallPhone(String number) {
        if (CollectionUtils.isNullOrEmpty(number)) {
            showToast("号码不能为空！");
        } else {
            // 拨号：激活系统的拨号组件
            Intent intent = new Intent(); // 意图对象：动作 + 数据
            intent.setAction(Intent.ACTION_CALL); // 设置动作
            Uri data = Uri.parse("tel:" + number); // 设置数据
            intent.setData(data);
            startActivity(intent); // 激活Activity组件
        }
    }

    @Override
    public void onResume() {
        super.onResume();
         token= TokenUtils.getToken();
        if (!CollectionUtils.isNullOrEmpty(token)){
            Login_ok(token);
        }else {
            Login_no();
        }
    }

    @Override
    protected void loadData(boolean isRefresh) {}
    //登入成功
    private void Login_ok(String token) {
        if (!CollectionUtils.isNullOrEmpty(token)){
            mBinding.score.setVisibility(View.VISIBLE);
            mBinding.loginNo.setVisibility(View.GONE);
            mBinding.loginOk.setVisibility(View.VISIBLE);
            if (!BaseAppLication.getInstance().ispage()){
                BaseAppLication.getInstance().setIspage(true);
            }
            getUser();
            BaseAppLication.getInstance().setIslogin(true);
        }else {
            BaseAppLication.getInstance().setIslogin(false);
        }
    }

    //退出登入
    private void Login_no() {
        mBinding.loginNo.setVisibility(View.VISIBLE);
        mBinding.loginOk.setVisibility(View.GONE);
        mBinding.username.setText("");
        mBinding.score.setVisibility(View.GONE);
        mBinding.nameCertification.setText("");
        mBinding.cartCertification.setText("");
        token="";
        mBinding.ncertification.setOnClickListener(v -> {
            if (!CollectionUtils.isNullOrEmpty(token)){
                if (BaseAppLication.getInstance().getIs_realname()==0)
                startActivityForResult(RealNameActivity.class,99,null,true);
            }else {
                startActivityForResult(LoginActivity.class,99,null,true);
            }
            });
        mBinding.ccertification.setOnClickListener(v -> {
            if (!CollectionUtils.isNullOrEmpty(token)){
                if (BaseAppLication.getInstance().getIs_realname()==0)
                startActivityForResult(CartCertificationActivity.class,99,null,true);
            }else {
                startActivityForResult(LoginActivity.class,99,null,true);
            }
        });
        mBinding.logo.setImageResource(R.mipmap.avator);
        BaseAppLication.getInstance().setIslogin(false);
    }
    /**
     * 用户权限处理,
     * 如果全部获取, 则直接过.
     * 如果权限缺失, 则提示Dialog.
     * @param requestCode  请求码
     * @param permissions  权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions,  int[] grantResults) {
        switch (requestCode){
            case MY_PERMISSIONS_REQUEST_CALL_PHONE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 授权成功，继续打电话
                    if (!CollectionUtils.isNullOrEmpty(AppConfig.tel))
                        CallPhone(AppConfig.tel);
                } else {
                    showToast("电话授权失败！");
                }
                break;
            }
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        loadData(true);
    }

    public void getUser() {
        String token= TokenUtils.getToken();
        if (!CollectionUtils.isNullOrEmpty(token)){
            OkGo.get(AppConfig.ReadUrl)
                    .tag(this)
                    .execute(new NoDialogCallback<Object>(getActivity()){
                        @Override
                        public void onSuccess(Response<Object> response) {
                            super.onSuccess(response);
                            if (!CollectionUtils.isNullOrEmpty(response.body())){
                                String data=GsonUtils.GsonString(response.body());
                                try {
                                    JSONObject json=new JSONObject(data);
                                    UserData userData=new UserData();
                                    //阿里云推送绑定手机号码
                                  int id=  json.getInt("id");
                                    BaseAppLication.getInstance().getPushService().bindAccount(id+"",WoFragment.this);
                                    userData.setAvatar(json.getString("avatar"));
                                    userData.setMobile(json.getString("mobile"));
                                    userData.setSignature(json.getString("signature"));
                                    userData.setIs_realname(json.getInt("is_realname"));
                                    userData.setIs_driver(json.getInt("is_driver"));
                                   String recommend= json.getString("recommend");
                                    String nickname= json.getString("nickname");
                                   CacheUtils.getInstance().put("recommend",recommend);
                                    CacheUtils.getInstance().put("nickname",nickname);
                                    mBinding.username.setText(nickname);
                                    BaseAppLication.getInstance().setIs_realname(userData.getIs_realname());
                                    if (!CollectionUtils.isNullOrEmpty(userData.getAvatar())){
                                        Glide.with(getActivity()).load(userData.getAvatar()).error(R.mipmap.avator).placeholder(R.mipmap.avator).into(mBinding.logo);
                                    }else {
                                        mBinding.logo.setImageResource(R.mipmap.avator);
                                    }
                                    if (userData.getIs_driver()==1){
                                        mBinding.cartCertification.setText("已认证");
                                        mBinding.cartCertification.setTextColor(getResources().getColor(R.color.order));
                                        mBinding.cartCertification.setOnClickListener(null);
                                    }else {
                                        mBinding.cartCertification.setTextColor(getResources().getColor(R.color.sdarkgray));
                                        mBinding.cartCertification.setText("未认证");
                                        mBinding.ccertification.setOnClickListener(v -> {startActivityForResult(CartCertificationActivity.class,99,null,true);});
                                    }
                                    CacheUtils.getInstance().put("realname",userData.getIs_realname());
                                    if (userData.getIs_realname()==1){
                                        mBinding.nameCertification.setText("已认证");
                                        mBinding.nameCertification.setTextColor(getResources().getColor(R.color.order));
                                        mBinding.ncertification.setOnClickListener(null);
                                    }else {
                                        mBinding.nameCertification.setText("未认证");
                                        mBinding.nameCertification.setTextColor(getResources().getColor(R.color.sdarkgray));
                                        mBinding.ncertification.setOnClickListener(v -> {startActivityForResult(RealNameActivity.class,99,null,true);});

                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        @Override
                        public void onError(Response<Object> response) {
                            super.onError(response);
                            showError(response);
                        }
                    });
        }
    }

    @Override
    public void onSuccess(String s) {

    }

    @Override
    public void onFailed(String s, String s1) {

    }
}
